from django.contrib.syndication.views import Feed
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
from django.http import Http404
from django.shortcuts import render, redirect

from shanshan.models import Article


def home(request):
    posts=Article.objects.all()
    paginator =Paginator (posts,2)  #每页显示2个
    page=request.get('page')
    try :
        post=paginator.page(page)
    except  PageNotAnInteger:
        post=paginator.page(1) #显示第一页
    except  EmptyPage:
        post=paginator.paginator(paginator.num_pages)
        #post_list = paginator.paginator(paginator.num_pages)
    # return render('home.html',{'post':post})
    return render(request ,'home.html',{'post':post})
#差别？

def detail(request, id):
    try:
        post = Article.objects.get(id=str(id))
        tags = post.tag.all()
    except Article.DoesNotExist:
        raise Http404
    return render(request, 'post.html', {'post': post, 'tags': tags})

#页面请求
def archives(request):
    try:
        post_list = Article.objects.all()
    except Article.DoesNotExist:
        raise Http404
    return render(request, 'archives.html', {'post_list': post_list,
                                             'error': False})
#request对象，模板名称，字典类型的可选参数，只返回一个包含有约定模板

# 文章对应标签
def search_tag(request, tag):
    try:
        post_list = Article.objects.filter(category__iexact=tag)
    except Article.DoesNotExist:
        raise Http404
    return render(request, 'tag.html', {'post_list': post_list})

#关于我
def about_me(request):
    return render(request, 'aboutme.html')


def blog_search(request):
    if 's' in request.GET:
        s = request.GET['s']
        if not s:
            return render(request, 'home.html')
        else:
            post_list = Article.objects.filter(title__icontains=s)
            return render(request, 'archives.html', {'post_list': post_list,
                                                     'error':
                                                     len(post_list) == 0})
    return redirect('/')


class RSSFeed(Feed):
    title = 'RSS feed - article'
    link = "feeds/posts/"
    description = 'RSS feed - blog posts'

    #@property
    def items(self):
        return Article.objects.order_by('-date_time')

    def item_title(self, item):
        return item.title

    def item_pubdate(self, item):
        return item.date_time

    def item_description(self, item):
        return item.content
